import { $cache } from '@/plugins'
import type { Ref } from 'vue'
import { ref } from 'vue'

interface Config {
  expires?: number
  isSession?: boolean
}
class CachedVariableManager<T> {
  public valueRef: Ref<T | undefined> = ref<T>()
  public cacheKey: string
  private config: Config

  constructor(
    cacheKey: string,
    initValue: T | undefined = undefined,
    config: Config = {
      isSession: false,
      expires: Number.MAX_SAFE_INTEGER
    }
  ) {
    this.cacheKey = cacheKey
    this.config = config
    if (config.isSession) this.clearValue()
    // 这里不必通知，因为对象在创建时，还没有值订阅者
    this.setValue($cache.get(cacheKey) || initValue)
  }
  getValue(): T | undefined {
    return this.valueRef.value
  }
  getValueRef(): Ref<T | undefined> {
    this.getValue()
    return this.valueRef
  }
  setValue(value: T, expires?: number) {
    this.valueRef.value = value
    this.cache(expires)
  }
  private cache(expires?: number) {
    $cache.set(this.cacheKey, this.getValue(), { expires: expires || this.config.expires })
  }
  clearValue() {
    $cache.remove(this.cacheKey)
    this.valueRef.value = undefined
  }
}
export default CachedVariableManager
